package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**
     * 定义Socket监听的端口号
     */
    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {
        // 加载解析相关的配置，web.xml
//        loadServlet();
        // 加载解析相关的配置
        loadConfig();

        // 定义一个线程池
        int corePoolSize = 10;  // 初始化大小
        int maximumPoolSize = 50; // 最大大小
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        /**
         完成Minicat 1.0版本
         需求：游览器请求http://localhost:8080，返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("======>>>>Minicat start on port:" + port);

//        while (true) {
//            Socket socket = serverSocket.accept();
//            // 有了socket，接收到请求，获取输出流
//            OutputStream outputStream = socket.getOutputStream();
//            String data = "Hello Minicat!";
//            String responeText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
//            outputStream.write(responeText.getBytes());
//            socket.close();
//        }

        /**
         * 完成Minicat 2.0版本
         * 需求：封装Request和Response对象，返回html静态资源文件
         */
//        while (true) {
//            Socket socket = serverSocket.accept();
//            InputStream inputStream = socket.getInputStream();
////            // 从输入流中获取请求信息
////            int count  = 0;
////            while (count == 0) {
////                count = inputStream.available();
////            }
////
////            byte[] bytes = new byte[count];
////            inputStream.read(bytes);
////            System.out.println("=========>>>>>请求信息：" + new String(bytes));
//
//            // 封装Request对象和Respone对象
//            Request request = new Request(inputStream);
//            Response response = new Response(socket.getOutputStream());
//
//            response.outputHtml(request.getUrl());
//            socket.close();
//        }

        /**
         * 完成Minicat 3.0版本
         * 需求：可以请求动态资源（Servlet）
         */
//        while (true) {
//            Socket socket = serverSocket.accept();
//            InputStream inputStream = socket.getInputStream();
//
//            // 封装Request对象和Respone对象
//            Request request = new Request(inputStream);
//            Response response = new Response(socket.getOutputStream());
//
//            if (servletMap.get(request.getUrl()) == null) {
//                response.outputHtml(request.getUrl());
//            } else {
//                // 动态资源Servlet请求
//                HttpServlet httpServlet = servletMap.get(request.getUrl());
//                httpServlet.service(request, response);
//            }
//
//            socket.close();
//        }

        /**
         * 多线程改造（不使用线程池）
         */
//        while (true) {
//            Socket socket = serverSocket.accept();
//            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
//            requestProcessor.start();
//        }

//        System.out.println("=====>>>>使用线程池进行多线程改造");
        /**
         * 多线程改造（使用线程池）
         */
//        while (true) {
//            Socket socket = serverSocket.accept();
//            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
//            threadPoolExecutor.execute(requestProcessor);
//        }

        /**
         * 完成Minicat 4.0版本
         * 需求：在已有Minicat基础上进一步扩展，模拟出webapps部署效果 磁盘上放置一个webapps目录，webapps中可以有多个项目
         */
        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessorV4 requestProcessorV4 = new RequestProcessorV4(socket, hosts, webappsPath);
            threadPoolExecutor.execute(requestProcessorV4);
        }
    }

    private Map<String, HttpServlet> servletMap = new HashMap<>();

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletNameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletNameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletClassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletClassElement.getStringValue();

                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private String webappsPath;
    private Map<String, Map<String, Map<String, HttpServlet>>> hosts = new HashMap<>();

    /**
     * 加载并解析配置文件
     */
    private void loadConfig() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            //解析server.xml
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            Element element = (Element) rootElement.selectSingleNode("//Connector");
            port = Integer.parseInt(element.attributeValue("port"));

            List<Element> hostsEle = rootElement.selectNodes("//Host");//获取host

            for (int i = 0; i < hostsEle.size(); i++) {
                String hostName = hostsEle.get(i).attributeValue("name");

                //项目集
                Map<String, Map<String, HttpServlet>> contexts = new HashMap<>();
                webappsPath = hostsEle.get(i).attributeValue("appBase");//host对应项目路径路径
                webappsPath = webappsPath.replaceAll("\\\\", "/");

                File file = new File(webappsPath);
                if (file.exists() && !file.isFile()) {

                    File[] files = file.listFiles();
                    for (int j = 0; j < files.length; j++) {
                        String webPath = files[j].getPath();//项目路径
                        //单个项目文件名
                        String fileName = webPath.replace(file.getPath() + "\\", "");
                        //读取web.xml文件
                        File webXml = new File(webPath + "\\web.xml");
                        InputStream resourceAsStreamWeb = new FileInputStream(webXml);
                        SAXReader saxReaderWeb = new SAXReader();
                        Map<String, HttpServlet> wrapper = new HashMap<String, HttpServlet>();
                        //解析各个项目web.xml
                        Document documentWeb = saxReaderWeb.read(resourceAsStreamWeb);
                        Element rootElementWeb = documentWeb.getRootElement();

                        List<Element> selectNodes = rootElementWeb.selectNodes("//servlet");
                        for (int k = 0; k < selectNodes.size(); k++) {
                            Element elementWeb = selectNodes.get(k);
                            // <servlet-name>lagou</servlet-name>
                            Element servletnameElement = (Element) elementWeb.selectSingleNode("servlet-name");
                            String servletName = servletnameElement.getStringValue();
                            // <servlet-class>server.LagouServlet</servlet-class>
                            Element servletclassElement = (Element) elementWeb.selectSingleNode("servlet-class");

                            String servletClass = servletclassElement.getStringValue();//class绝对路径
                            // 根据servlet-name的值找到url-pattern
                            Element servletMapping = (Element) rootElementWeb.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                            // /lagou
                            String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                            String pakageDir = webPath.replaceAll("\\\\", "/");
                            MyClassLoader loader = new MyClassLoader(pakageDir + "/");
                            Class<?> clazz = loader.findClass(servletClass);
                            wrapper.put(urlPattern, (HttpServlet) clazz.getClassLoader().loadClass(servletClass).newInstance());
                        }
                        contexts.put(fileName, wrapper);
                    }
                }

                if ("localhost".equalsIgnoreCase(hostName)) {
                    hosts.put("127.0.0.1", contexts);//增加127.0.0.1 对应 localhost
                }
                hosts.put(hostName, contexts);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * Minicat的程序启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
